import { useState } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByIcon from "@/components/ui/ByIcon";
import PopupMaterial from "./PopupMaterial";
import ByPopup from "@/components/ui/ByPopup";
import PopupPlanExecution from "@/pages/index/components/PopupPlanExecution";

import useAuth from "@/hooks/useAuth";
import request from "@/utils/request";
import ApiCrm from "@/api/crm";

type MenuItem = {
  label: string;
  icon: string;
  url?: string;
  authCode?: string | string[];
};

const appMenus: { title: string; menus: MenuItem[]; color: string[] }[] = [
  {
    title: "施工",
    color: ["#b8a7f750", "#7151ea"],
    menus: [
      {
        label: "计划拟定",
        icon: "PlanFormulation",
        authCode: "WeiXinApp_InsPlanManage",
        url: "/packageWork/pages/plan/index",
      },
      {
        label: "计划执行",
        icon: "PlanExecute",
        authCode: "WeiXinApp_InsPlanExecute",
      },
      {
        label: "施工验收",
        icon: "ConstructionAcceptance",
        authCode: "WeiXinApp_ConstructAcceptanceView",
        url: "/packageProject/pages/acceptance/list",
      },
      {
        label: "工程巡检",
        icon: "EngineeringInspection",
        authCode: "WeiXinApp_Insepction",
        url: "/packageProject/pages/inspection/record",
      },
      {
        label: "施工现场",
        icon: "Monitor",
        authCode: "WeiXinApp_Monitor",
        url: "/packageProject/pages/mokan/index",
      },
      {
        label: "工程款",
        icon: "Funds",
        authCode: [
          "WeiXinApp_PaymentApply_View",
          "WeiXinApp_PaymentApply_Menu",
        ],
        url: "/packageProject/pages/engineeringFunds/list",
      },
      {
        label: "预算",
        icon: "Budget",
        authCode: "WeiXinApp_BudgetView",
        url: "/packageProject/pages/budget/index",
      },
      {
        label: "整改",
        icon: "Correction",
        authCode: "WeiXinApp_Rectification",
        url: "/packageProject/pages/inspection/correction",
      },
    ],
  },
  {
    title: "材料",
    color: ["#ffe2b750", "#fba83f"],
    menus: [
      {
        label: "选材",
        icon: "Material",
        // authCode: "WeiXinApp_MaterialChoose_ChooseAgain",
        authCode: "WeiXinApp_MobileChooseMaterial",
        url: "/packageProject/pages/material/index",
      },
      {
        label: "材料申报",
        icon: "MaterialApply",
        authCode: "WeiXinApp_SelfMaterielApply",
        url: "/packageProject/pages/materialDeclaration/list",
      },
      {
        label: "材料确认",
        icon: "MaterialConfirm",
        // WeiXinApp_MaterielArrivalCheckView、WeiXinApp_MaterielArrivalCheck
        authCode: ["WeiXinApp_MaterielArrivalCheckView"],
        url: "/packageProject/pages/materialConfirm/list",
      },
    ],
  },
  {
    title: "工人",
    color: ["#0088ff2b", "#0088ff"],
    menus: [
      {
        label: "工人派工",
        icon: "DispatchWork",
        authCode: "WeiXinApp_WorkerDistirbute",
        url: "/packageWork/pages/dispatch/index",
      },
      {
        label: "工人工费",
        icon: "Wages",
        authCode: "WeiXinApp_WorkerPayrollApply",
        url: "/packageWork/pages/wages/index",
      },
    ],
  },
  {
    title: "项目",
    color: ["#f9202010", "#ff3a3a"],
    menus: [
      {
        label: "罚款",
        icon: "Fine",
        authCode: [
          "WeiXinApp_FineManagerRoot_Edit",
          "WeiXinApp_FineManagerRoot_View",
        ],
        url: "/packageProject/pages/fine/list",
      },
      {
        label: "收款",
        icon: "ReciveMoney",
        authCode: "WeiXinApp_ViewReciptBill",
        url: "/packageProject/pages/finance/index",
      },
      {
        label: "签报",
        icon: "QianBao",
        authCode: "WeiXinApp_Shenpi_view",
        url: "/packageProject/pages/report/list",
      },
      {
        label: "售后服务",
        icon: "AfterSales",
        authCode: "WeiXinApp_Shouhou_view",
        url: "/packageProject/pages/afterSales/list",
      },
      {
        label: "项目经理结算",
        icon: "Settlement",
        authCode: "WeiXinApp_GafferJS_view",
        url: "/packageProject/pages/settlement/index",
      },
    ],
  },
];

const ApplicationItem = ({
  intentCustomerId,
  projectid,
  item,
  colors,
  onPopup,
}: {
  intentCustomerId: number;
  projectid?: number | string;
  item: MenuItem;
  colors: string[];

  onPopup: (type: string) => void;
}) => {
  const navigator = async () => {
    const { icon } = item;

    if (icon === "PlanFormulation") {
      // 需要判断是都已完成计划拟定（没有接口）
      const path = await request(
        {
          url: ApiCrm.getConstructionPlanDetail,
          data: { intentionCustomerId: intentCustomerId },
        },
        { showErrorToast: false }
      )
        .then((res: any) => {
          // state == 88 表示已提交，不可编辑
          return res.formConstructionPlan[0].state == 88 ? "detail" : "index";
        })
        .catch(() => "index");

      Taro.navigateTo({
        url: `/packageWork/pages/plan/${path}?intentCustomerId=${intentCustomerId}`,
      });
    } else if (icon === "Material") {
      // 选材
      onPopup("Material");
    } else if (icon === "PlanExecute") {
      onPopup("PlanExecute");
    } else {
      const url =
        icon === "Monitor" && !projectid
          ? "/packageProject/pages/mokan/add"
          : item.url;
      Taro.navigateTo({ url: url + `?intentCustomerId=${intentCustomerId}` });
    }
  };

  return (
    <ByCol span={3} className="w-[120px] text-center my-2">
      <View onClick={navigator}>
        <View
          className="flex-center mx-auto w-[110px] h-[110px] rounded-[30px] border-1"
          style={{ backgroundColor: colors[0], borderColor: colors[0] }}
        >
          <ByIcon name={item.icon} size={66} color={colors[1]} />
        </View>
        <View className="text-sm text-second mt-2">{item.label}</View>
      </View>
    </ByCol>
  );
};

export default ({
  intentCustomerId,
  projectid,
}: {
  intentCustomerId: number;
  projectid?: string | number;
}) => {
  const [seleted, setSelected] = useState<MenuItem>();

  const getNode = () => {
    switch (seleted!.icon) {
      case "Material":
        return PopupMaterial;
      case "PlanExecute":
        return PopupPlanExecution;
    }
  };

  const PopupNode = seleted ? getNode() : undefined;
  const getAuth = useAuth();

  return (
    <>
      {appMenus.map((item, index) => (
        <View key={index}>
          <View className="mb-2">{item.title}</View>
          <View className="mb-5">
            <ByRow wrap>
              {item.menus.map((subItem, subIndex) =>
                getAuth(subItem.authCode) ? (
                  <ApplicationItem
                    key={subIndex}
                    item={subItem}
                    colors={item.color}
                    projectid={projectid}
                    intentCustomerId={intentCustomerId}
                    onPopup={() => setSelected(subItem)}
                  />
                ) : null
              )}
            </ByRow>
          </View>
        </View>
      ))}

      {PopupNode && (
        <ByPopup position="bottom">
          <PopupNode
            intentCustomerId={intentCustomerId}
            onCancel={() => setSelected(undefined)}
          />
        </ByPopup>
      )}
    </>
  );
};
